<!--
 * @Description:第二十七章（自定义指令directive）指令拖曳案例
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-20 00:05:07
-->
<template>
  <div>
    <h1>第二十七章（自定义指令directive）指令拖曳案例</h1>
    <div class="box" v-move>
      <div class="header"></div>
      <div>内容</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { Directive, DirectiveBinding } from 'vue'

const vMove: Directive<any, void> = (el: HTMLElement, binding: DirectiveBinding) => {
  let moveElement: HTMLDivElement = el.firstElementChild as HTMLDivElement
  console.log('moveElement: ', moveElement)
  const mousedown = (e: MouseEvent) => {
    let x = e.clientX - el.offsetLeft
    let y = e.clientY - el.offsetTop

    const move = (e: MouseEvent) => {
      console.log('move e: ', e)
      el.style.left = e.clientX - x + 'px'
      el.style.top = e.clientY - y + 'px'
    }
    document.addEventListener('mousemove', move)

    moveElement.addEventListener('mouseup', () => {
      document.removeEventListener('mousemove', move)
    })
  }
  moveElement.addEventListener('mousedown', mousedown)
}
</script>
<style scoped lang="less">
h1,
h2,
h3,
hr {
  margin: 10px 0;
}

.box {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  .header {
    height: 20px;
    background: black;
    cursor: move;
  }
}
</style>
